package com.example.programming.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.programming.common.Result;
import com.example.programming.common.tools.BaseController;
import com.example.programming.sys.entity.EduChapter;
import com.example.programming.sys.entity.EduCourse;
import com.example.programming.sys.entity.EduVideo;
import com.example.programming.sys.entity.vo.*;
import com.example.programming.sys.mapper.EduChapterMapper;
import com.example.programming.sys.mapper.EduCourseMapper;
import com.example.programming.sys.mapper.EduVideoMapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 前端控制器 chrimer
 * </p>
 *
 * @author chrimer
 * @since 2020-09-07
 */
@RestController
@RequestMapping("/sys/educourse")
@CrossOrigin
public class EduCourseController extends BaseController {
    @Autowired
    EduCourseMapper eduCourseMapper;
    @Autowired
    private EduChapterMapper eduChapterMapper;
    @Autowired
    private EduVideoMapper eduVideoMapper;

    @ApiImplicitParams({
    @ApiImplicitParam(name = "pageNum",paramType = "query",value = "当前页码",required = true),
    @ApiImplicitParam(name = "pageSize",paramType = "query",value = "每页显示记录数",required = true)
    })
    @ApiOperation(value = "分页获取EduCourse信息")
    @RequestMapping(method= RequestMethod.POST,value="/page")
    public Result page(@RequestBody PageVo pageVo) {
        String id = pageVo.getId();
        long pageNum = pageVo.getPageNum();
        long pageSize = pageVo.getPageSize();
        Result result = new Result();
        System.out.println(pageNum);
        System.out.println(pageSize);
        Page<EduCourse> page = new Page<EduCourse>(pageNum, pageSize);
        EduCourse parms = new EduCourse();
        QueryWrapper<EduCourse> warpper = new QueryWrapper<EduCourse>(parms);

        warpper.eq("subject_id", id);

        result.setData(eduCourseMapper.selectPage(page, warpper));
        return result;
    }
    @ApiOperation(value = "保存修改EduCourse信息")
    @RequestMapping(method= RequestMethod.POST,value="/save")
    public Result save(@RequestBody EduCourse entity) {
        Result result = new Result();
        if (entity.getId() == null) {
            eduCourseMapper.insert(entity);
        } else {
            eduCourseMapper.updateById(entity);
        }
        return result;
    }
    @ApiOperation(value = "按id删除EduCourse，可以传入多个id用，隔开")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ids",paramType = "query",value = "传入的id串，用，隔开",required = true)
    })
    @RequestMapping(method= RequestMethod.DELETE,value="/delete")
    public Result delete( String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
        eduCourseMapper.deleteBatchIds(deleteIds);
        return result;
    }

    @ApiOperation(value = "分页课程列表")
    @PostMapping(value = "{page}/{limit}")
    public Result pageList(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @RequestBody() CourseQueryVo courseQuery) {
        Result result = new Result();

        Page<EduCourse> pageParam = new Page<EduCourse>(page, limit);
//        Map<String, Object> map = courseService.pageListWeb(pageParam, courseQuery);

        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }


        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
//            queryWrapper.orderByDesc("price");
            queryWrapper.orderByAsc("price");
        }

        eduCourseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        result.setData(map);
        return result;
    }

    @GetMapping("getCourseById/{id}")
    public Result getCourseById(@PathVariable("id") String id, HttpServletRequest request) {
        Result result = new Result();
        //查询课程信息和讲师信息
//        QueryWrapper<Object> objectQueryWrapper = new QueryWrapper<>();
//        eduCourseMapper.selectList(null);
        CourseWebVo courseWebVo = eduCourseMapper.selectInfoWebById(id);

//        查询当前课程的章节信息
//        List<ChapterVo> chapterVoList = eduChapterMapper.getChapter(courseId);
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", id);
        List<EduChapter> chapterList = eduChapterMapper.selectList(chapterQueryWrapper);

        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", id);
        List<EduVideo> videoList = eduVideoMapper.selectList(videoQueryWrapper);

        List<ChapterVo> finalList = new ArrayList<>();

        for (int i = 0; i < chapterList.size(); i++) {
            EduChapter chapter = chapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            finalList.add(chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();

            for (int j = 0; j < videoList.size(); j++) {
                EduVideo video = videoList.get(j);
                if (video.getChapterId().equals(chapter.getId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        courseWebVo.setChapterList(finalList);
        result.setData(courseWebVo);
        return result;
    }

    @RequestMapping(method= RequestMethod.POST,value="/getCourseByName")
    public Result getCourseByName(@RequestBody CourseQueryVo courseQueryVo) {
        String coursename = courseQueryVo.getTitle();
        System.out.println(courseQueryVo);
        Result result = new Result();
        EduCourse parms = new EduCourse();
        Page<EduCourse> page = new Page<EduCourse>(1, 500);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<EduCourse>(parms);
        if(coursename!=null&&!"".equals(coursename)){
            wrapper.like("title",coursename);
        }
        result.setData(eduCourseMapper.selectPage(page,wrapper));
        return result;
    }
}
